const form = document.querySelector('#gpt-form');
const submitBtn = document.querySelector('#submit-btn');
const loadingSpinner = document.querySelector('#loading-spinner');

form.addEventListener('submit', async function(event) {
    event.preventDefault();
    const inputText = document.querySelector('#input_text').value.trim();
    if (inputText.length === 0) {
        return;
    }

    setLoadingState(true);
    submitBtn.disabled = true;

    try {
        const response = await fetch('/generate', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ text: inputText })
        });
        const data = await response.json();
        if (data.generated_text) {
            const generatedText = data.generated_text.trim();
            document.querySelector('#input_text').value = '';
            renderGeneratedText(generatedText);
        }
    } catch (error) {
        console.error(error);
    } finally {
        setLoadingState(false);
        submitBtn.disabled = false;
    }
});

function renderGeneratedText(text) {
    const container = document.createElement('textarea');
    container.style.display = 'block';
    container.style.margin = 'auto';
    container.style.height = '100px';
    container.style.width = '700px';
    container.style.boxSizing = 'border-box';
    container.style.marginBottom = '20px';
    const outputTextArea = document.querySelector('#output_text');

    if (outputTextArea) {
        outputTextArea.value = text;
    } else {
        container.textContent = `response: ${text}`;
        document.querySelector('.gpt-form').appendChild(container);
    }
}



function setLoadingState(isLoading) {
    if (isLoading) {
        loadingSpinner.style.visibility = 'visible';
    } else {
        loadingSpinner.style.visibility = 'hidden';
    }
}